import React from 'react'
import PropTypes from 'prop-types';
class Input extends React.Component {
constructor(props) {
    super(props)
    this.state = {
      label: ''
    }
  }
  render() {
    return <p>
      <input value={this.state.label} onChange= {this.changName}/>
        <br/>
      <button onClick={this.addItem}>新增</button>
    </p>
  }

  changName = (e) => {
    this.setState({
      label: e.target.value
    })
  }

  addItem = () =>{
    const {label} = this.state
    const {addTile} =  this.props;
    if(label) {
      addTile({id: Math.random(1,100), label, price: 33})

      this.setState({
        label: ''
      })
    }
  }
}
Input.propTypes = {
  addTile: PropTypes.func.isRequired
}

class Footer extends React.Component {
  constructor(props) {
    super(props)
  }
  render() {
    return <div>
      <p> {this.props.footerTitle}</p>
    </div>
  }
  componentDidUpdate() {
    console.log(` Footer component is DidUpdate`);
  }
  shouldComponentUpdate(nextProps, nextState) {
    if(nextProps.footerTitle !== this.props.footerTitle) {return true}
    return false;
  }
}

class List extends React.Component {
    constructor(props){
        super(props)
        this.state = {
            productList: [
                {
                    id: 1,
                    label: 'Nike',
                    price: 339
                },
                {
                    id: 2,
                    label: 'Adidas',
                    price: 332
                },
                {
                    id: 3,
                    label: 'Kappa',
                    price: 331
                }
            ],
            footerTitle: '底部测试'
        }
        // this.handleName = this.handleName.bind(this)
    }
    render() {
        const {state} = this;
        return <div>
                <Input addTile={this.onAddTile}/>
                <ul className='list'>
                    {this.state.productList.map( (v) => {
                        return <li key={v.id} className='list-item'>{v.label} ---- {v.price}</li>
                    })}
                </ul>
                <Footer footerTitle={this.state.footerTitle}/>
            </div>
    }
   
    onAddTile = (item) => {
        const { productList } = this.state;
        productList.push(item);
        this.setState({
          productList
        })
    }
}

export default List